package cn.hist.hfp.service;

import cn.hist.hfp.converter.CommodityProducerConverter;
import cn.hist.hfp.entity.CommodityProducer;
import cn.hist.hfp.exception.ResourceNotFoundException;
import cn.hist.hfp.repository.CommodityProducerRepository;
import cn.hist.hfp.vo.CommodityProducerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CommodityProducerService {

    private final
    CommodityProducerRepository commodityProducerRepository;

    private final CommodityProducerConverter commodityProducerConverter;

    @Autowired
    public CommodityProducerService(CommodityProducerRepository commodityProducerRepository, CommodityProducerConverter commodityProducerConverter) {
        this.commodityProducerRepository = commodityProducerRepository;
        this.commodityProducerConverter = commodityProducerConverter;
    }

    public CommodityProducerVO create(CommodityProducer commodityProducer) {
        return commodityProducerConverter.converter(commodityProducerRepository.save(commodityProducer));
    }

    public CommodityProducer findOne(int id) {
        Optional<CommodityProducer> optionalCommodityProducer = commodityProducerRepository.findById(id);
        if (optionalCommodityProducer.isPresent()) {
            return optionalCommodityProducer.get();
        }
        throw new ResourceNotFoundException();
    }

    public CommodityProducerVO findOneVO(int id) {
        return commodityProducerConverter.converter(findOne(id));
    }

    public List<CommodityProducerVO> findAll() {
        return commodityProducerConverter.converter(commodityProducerRepository.findAll());
    }

    public CommodityProducerVO update(CommodityProducer commodityProducer) {
        return commodityProducerConverter.converter(commodityProducerRepository.save(commodityProducer));
    }

    public int delete(int id) {
        Optional<CommodityProducer> optionalCommodityProducer = commodityProducerRepository.findById(id);
        optionalCommodityProducer.ifPresent(commodityProducerRepository::delete);
        return commodityProducerRepository.findById(id).isPresent() ? 0 : 1;
    }
}
